import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Text, Input, Picker} from '@tarojs/components'
import {AtIcon, AtCard} from 'taro-ui'
import {TicketRecordListItem, TicketRecordList} from 'src/utils/server.interface'
import {user} from '../../utils/user.service'
import {http} from '../../utils/http'
import {vcmonitor} from "../../utils/tools";
import {MY_SUPPLIER_IDENTITY_RECORD, LIST_TICKET_RECORD, TARO_ENV} from '../../constants/api'
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import Index from "../components/water-mark/index";
import './check-ticket.scss'

export default class TicketRecord extends Component {
  state: {
    supplier_id: string
    supplierChecked: string
    supplierList: any
    supplierIndex: number
    ticketList: TicketRecordListItem[]
    inputText: string
    loadMoreStatus: "more" | "loading" | "noMore"
  } = {
    ticketList: [],
    loadMoreStatus: 'loading',
  }

  async componentDidShow() {
    vcmonitor(this)
  }

  async UNSAFE_componentWillMount() {
    if (TARO_ENV === 'weapp') {
      Taro.hideShareMenu()
    }
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/index/index'})
      }, 1500)
      return
    }
    const userIdentity = await http.get(MY_SUPPLIER_IDENTITY_RECORD, {})
    if (userIdentity) {
      let supplierChecked = ''
      let supplier_id = ''
      let supplierIndex = Taro.getStorageSync('supplierIndexRecord') || 0
      if (userIdentity.supplierUserList.length > 0) {
        supplierIndex = userIdentity.supplierUserList.length >= supplierIndex ? userIdentity.supplierUserList.length - 1 : supplierIndex
        supplierChecked = userIdentity.supplierUserList[supplierIndex].company
        supplier_id = userIdentity.supplierUserList[supplierIndex].supplier_id
        Taro.setStorageSync('supplierIndexRecord', supplierIndex)
      }
      const recordList = await http.get<TicketRecordList>(LIST_TICKET_RECORD, {
        nowPage: 1,
        supplier_id,
        k: this.state.inputText
      })
      if (recordList) {
        if (recordList && !recordList.lastPage) {
          this.setState({loadMoreStatus: 'more'})
        } else {
          this.setState({loadMoreStatus: 'noMore'})
        }
        this.setState({
          supplierChecked,
          supplier_id,
          supplierList: userIdentity.supplierUserList,
          ticketList: recordList.list
        })
      }
    } else {
      return
    }
  }

  page = 1

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'}, async () => {
        this.page++
        const ticketList = await this.getData(this.page)
        const old = this.state.ticketList
        if (ticketList) {
          this.setState({ticketList: [...old, ...ticketList]})
        }
      })
    }
  }

  inputChange(value) {
    this.setState({inputText: value.detail.value})
  }

  async submit() {
    const {supplierIndex} = this.state
    if (supplierIndex < 0) {
      Taro.showToast({
        title: '请先选择供应商',
        icon: 'none'
      })
      return
    }
    Taro.showLoading({title: '加载中...'})
    const recordList = await http.get<TicketRecordList>(LIST_TICKET_RECORD, {
      nowPage: 1,
      supplier_id: this.state.supplier_id,
      k: this.state.inputText
    })
    if (recordList) {
      if (recordList && recordList.pageNumber <= recordList.totalPage) {
        this.setState({ticketList: recordList.list, loadMoreStatus: 'more'})
      } else {
        this.setState({ticketList: recordList.list, loadMoreStatus: 'noMore'})
      }
      Taro.hideLoading()
    } else {
      Taro.showToast({title: '未找到验证码信息', icon: 'none'})
    }
  }

  async getData(page) {
    const recordList = await http.get<TicketRecordList>(LIST_TICKET_RECORD, {
      supplier_id: this.state.supplier_id,
      nowPage: page,
      k: this.state.inputText
    })
    if (recordList && recordList.pageNumber <= recordList.totalPage) {
      this.setState({loadMoreStatus: 'more'})
      return recordList.list
    } else {
      this.setState({loadMoreStatus: 'noMore'})
      return []
    }
  }

  onChange(e) {
    const {supplierList} = this.state
    const supplierIndex = Number(e.detail.value)
    const supplier_id = supplierList[supplierIndex].supplier_id
    const supplierChecked = supplierList[supplierIndex].company
    this.setState({supplier_id, supplierIndex, supplierChecked}, async () => {
      Taro.setStorageSync('supplierIndexRecord', supplierIndex)
      const ticketList = await this.getData(this.page)
      if (ticketList.length <= 0) {
        this.setState({ticketList, loadMoreStatus: 'noMore'})
      } else {
        this.setState({ticketList, loadMoreStatus: 'more'})
      }
    })
  }

  render() {
    const {inputText, ticketList, supplierList, supplierChecked, supplierIndex} = this.state
    return (
      <View className='check-ticket-root'>
        <GzhAuth />
        <Index />
        <View className='head-bg'>
          <View className='header-bar'>
            <View className='head-picker'>
              {!!supplierList && supplierList.length > 1 &&
              <Picker value={supplierIndex} range={supplierList} rangeKey='company' onChange={this.onChange.bind(this)}>
                <View className={supplierChecked ? 'picker' : 'picker off'}>
                  {supplierChecked ? '供应商: ' + supplierChecked : '请先选择供应商'}
                  <Text>切换</Text>
                </View>
              </Picker>}
            </View>
          </View>
          <View className='input-box'>
            <View className='input input-i-cla'>
              <Input className={`${process.env.TARO_ENV}`} value={inputText} placeholderClass='input_pla'
                placeholder='手机号/验证码核销' onInput={this.inputChange.bind(this)}
              />
            </View>
            <View className='btn' onClick={this.submit.bind(this)}><AtIcon prefixClass='xxhz' value='sousuo2' size='18'
              color='#fff'
            /></View>
          </View>
        </View>
        <View className='content'>
          {ticketList.length > 0 && ticketList.map((item:any ,index) => <View className='card' key={index}>
            <AtCard title={item.tickets} extra={item.check_num ? `核销 ${item.check_num} 张` : ''}>
              <View className='is-team-appointment' />
              <View className='supplier text2'>供应商：{item.company}</View>
              {!!item.gname && <View className='supplier text2 supplier-gname'>商品名称：{ item.alias ? item.alias : item.gname}</View>}
              <View className='supplier text2'>客户姓名：{item.linkman}</View>
              <View className='supplier text2'>手机号：{item.phone}</View>
              {!!item.identity_num && <View className='supplier text2 supplier-gname'>身份证：{item.identity_num}</View>}
              <View className='date text2'>核销日期：{item.use_date}</View>
            </AtCard>
          </View>)}
        </View>
      </View>
    )
  }
}
